/* eslint-disable no-underscore-dangle,@typescript-eslint/explicit-module-boundary-types */
class UploadAdapter {
  constructor(loader, editor) {
    // The file loader instance to use during the upload.
    this.loader = loader
    this.editor = editor
  }

  // Starts the upload process.
  upload() {
    return this.loader.file
      .then(file => new Promise((resolve, reject) => {
        this.sendRequest(resolve, reject, file)
      }))
  }

  // Aborts the upload process.
  abort() {
    if (this.cancelRequest) {
      this.cancelRequest('操作被用户取消')
    }
  }

  // Initializes the XMLHttpRequest object using the URL passed to the constructor.
  sendRequest(resolve, reject, file) {
    const { upload } = this.editor
    if (typeof upload !== 'function') {
      reject('请传入 upload')
      return
    }

    const onUploadProgress = event => {
      if (event.lengthComputable) {
        this.loader.uploadTotal = event.total
        this.loader.uploaded = event.loaded
      }
    }

    // TODO 上传失败 出现 alert 提示问题 待处理
    const { request, cancel } = upload(file, onUploadProgress)
    this.cancelRequest = cancel
    request
      .then(res => {
        resolve({
          default: res
        })
      })
      .catch(err => {
        reject(err.message || `上传“${file.name}”失败，请重试`)
      })
  }
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function UploadAdapterPlugin(editor) {
  // Configure the URL to the upload script in your back-end here!
  editor.plugins.get('FileRepository').createUploadAdapter = loader => new UploadAdapter(loader, editor)
}
